// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/functions/sparksql/specialforms/spark-cast_hooks.h>
#include <pollux/common/strings/string_impl.h>
#include <pollux/type/timestamp_conversion.h>
#include <pollux/type/tz/time_zone_map.h>

namespace kumo::pollux::functions::sparksql {
    SparkCastHooks::SparkCastHooks(const pollux::core::QueryConfig &config)
        : config_(config) {
        const auto sessionTzName = config.sessionTimezone();
        if (!sessionTzName.empty()) {
            timestampToStringOptions_.timeZone = tz::locateZone(sessionTzName);
        }
    }

    Expected<Timestamp> SparkCastHooks::castStringToTimestamp(
        const StringView &view) const {
        auto conversionResult = util::fromTimestampWithTimezoneString(
            view.data(), view.size(), util::TimestampParseMode::kSparkCast);
        if (conversionResult.hasError()) {
            return melon::makeUnexpected(conversionResult.error());
        }

        auto sessionTimezone = config_.sessionTimezone().empty()
                                   ? nullptr
                                   : tz::locateZone(config_.sessionTimezone());
        return util::fromParsedTimestampWithTimeZone(
            conversionResult.value(), sessionTimezone);
    }

    template<typename T>
    Expected<Timestamp> SparkCastHooks::castNumberToTimestamp(T seconds) const {
        // Spark internally use microsecond precision for timestamp.
        // To avoid overflow, we need to check the range of seconds.
        static constexpr int64_t maxSeconds =
                std::numeric_limits<int64_t>::max() / Timestamp::kMicrosecondsInSecond;
        if (seconds > maxSeconds) {
            return Timestamp::fromMicrosNoError(std::numeric_limits<int64_t>::max());
        }
        if (seconds < -maxSeconds) {
            return Timestamp::fromMicrosNoError(std::numeric_limits<int64_t>::min());
        }

        if constexpr (std::is_floating_point_v<T>) {
            return Timestamp::fromMicrosNoError(
                static_cast<int64_t>(seconds * Timestamp::kMicrosecondsInSecond));
        }

        return Timestamp(seconds, 0);
    }

    Expected<Timestamp> SparkCastHooks::castIntToTimestamp(int64_t seconds) const {
        return castNumberToTimestamp(seconds);
    }

    Expected<std::optional<Timestamp> > SparkCastHooks::castDoubleToTimestamp(
        double value) const {
        if (MELON_UNLIKELY(std::isnan(value) || std::isinf(value))) {
            return std::nullopt;
        }
        return castNumberToTimestamp(value);
    }

    Expected<int32_t> SparkCastHooks::castStringToDate(
        const StringView &dateString) const {
        // Allows all patterns supported by Spark:
        // `[+-]yyyy*`
        // `[+-]yyyy*-[m]m`
        // `[+-]yyyy*-[m]m-[d]d`
        // `[+-]yyyy*-[m]m-[d]d *`
        // `[+-]yyyy*-[m]m-[d]dT*`
        // The asterisk `*` in `yyyy*` stands for any numbers.
        // For the last two patterns, the trailing `*` can represent none or any
        // sequence of characters, e.g:
        //   "1970-01-01 123"
        //   "1970-01-01 (BC)"
        return util::fromDateString(
            removeWhiteSpaces(dateString), util::ParseMode::kSparkCast);
    }

    Expected<float> SparkCastHooks::castStringToReal(const StringView &data) const {
        return util::Converter<TypeKind::REAL>::tryCast(data);
    }

    Expected<double> SparkCastHooks::castStringToDouble(
        const StringView &data) const {
        return util::Converter<TypeKind::DOUBLE>::tryCast(data);
    }

    StringView SparkCastHooks::removeWhiteSpaces(const StringView &view) const {
        StringView output;
        stringImpl::trimUnicodeWhiteSpace<true, true, StringView, StringView>(
            output, view);
        return output;
    }

    exec::PolicyType SparkCastHooks::getPolicy() const {
        return exec::PolicyType::SparkCastPolicy;
    }
} // namespace kumo::pollux::functions::sparksql
